//
//  MBWLMListViewController.m
//  Meboo
//
//  Created by kyo on 2023/10/25.
//

#import "MBWLMListViewController.h"
#import "MBWLMListCell.h"
#import "MBWLMTopicModel.h"
#import "NSModelDetailViewController.h"
#import "NSConversationViewController.h"
#import "NSWLMHeaderView.h"
#import "NSWLMFooterView.h"
#import "NSWLMNullView.h"
#import "NSUsageNumView.h"
#import "NSRongYunManager.h"
#import "NSMatchViewController.h"
#import "MBRefreshGifHeaderLottie.h"
//pop
#import "NSVipPopView.h"
@interface MBWLMListViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>
@property(nonatomic,strong) UIImageView *backImageView;
@property(nonatomic,strong) NSWLMHeaderView *headerView;
@property(nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic , assign) NSInteger clickNum;
@property (nonatomic , strong) NSWLMNullView *nullView;
@property (nonatomic , strong) NSUsageNumView *usageNumView;
@property (nonatomic , strong) MBRefreshGifHeaderLottie *refreshGifHeaderLottie;
//pop
@property(nonatomic,strong) NSVipPopView *vipPopView;
//刷新状态标识符
@property(nonatomic,assign) BOOL isVip;
@end

@implementation MBWLMListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    [self setupUI];
//    __WeakSelf
//    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [weakSelf getListData];
//    }];
    
    __WeakSelf
    [self.refreshGifHeaderLottie setJsonName:@"refresh.json"];
        self.collectionView.mj_header = self.refreshGifHeaderLottie;
    
    [self.refreshGifHeaderLottie setRefreshingBlock:^{
        [weakSelf getListData];
    }];
    
    
    [self getListData];
    [MBNotificationCenter addObserver:self selector:@selector(likeOrPass:) name:WLM_MODELDETAIL_LIKEPASS object:nil];
    [MBNotificationCenter addObserver:self selector:@selector(paySuccess) name:PAY_SUCCESS_NOTIFICATION object:nil];
    [MBNotificationCenter addObserver:self selector:@selector(chatSend) name:WLM_CHAT_SENDED object:nil];
    [[NSRongYunManager sharedManager] getRongCloudToken];
    self.isVip = [MBUserAccount defaultAccount].isVip;
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //    [self getListData];
    //因为本页面的显示与vip状态相关 每次进来 要判断vip是否发生了变化 有变化则刷新状态
    if (self.isVip != [MBUserAccount defaultAccount].isVip) {
        //有变化
        [self getListData];
        self.isVip = [MBUserAccount defaultAccount].isVip;
    }
}

#pragma mark - Private Method

- (void)chatSend {
//    MBWLMTopicModel *model = [MBWhoLikeMeDataManager sharedManager].listDataArr[self.clickNum];
//    [[MBWhoLikeMeDataManager sharedManager] topicLikeType:1 userId:model.userCodeFriend ?: model.friendUserCode success:^(BOOL success) {
//    }];
//    [self likePassResetData];
}

- (void)paySuccess {
    [self.collectionView reloadData];
}

- (void)getListData {
    [[MBWhoLikeMeDataManager sharedManager] getWhoLikeMeList:^(BOOL success) {
        [self.collectionView.mj_header endRefreshing];
        [self.headerView resetState];
        if (success && [MBWhoLikeMeDataManager sharedManager].listDataArr.count > 0) {
            [self.collectionView reloadData];
            self.collectionView.hidden = NO;
            self.nullView.hidden = YES;
            self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",[MBWhoLikeMeDataManager sharedManager].listDataArr.count];
        } else {
            self.collectionView.hidden = YES;
            self.nullView.hidden = NO;
            self.navigationController.tabBarItem.badgeValue = nil;//清空
        }
        
        if ([[MBWhoLikeMeDataManager sharedManager].wlmNum integerValue] > 0 && ![MBUserAccount defaultAccount].isVip) {
            self.usageNumView.hidden = NO;
            self.usageNumView.numLab.text = [MBWhoLikeMeDataManager sharedManager].wlmNum;
        } else {
            self.usageNumView.hidden = YES;
        }
    }];
}

-(void)likeOrPass:(NSNotification *)noti {
    NSInteger likeType = 1;
    if ([noti.object isEqualToString:@"1"]) {
        likeType = 1;
    }else{
        likeType = 2;
    }
    MBWLMTopicModel *model = [MBWhoLikeMeDataManager sharedManager].listDataArr[self.clickNum];
    
    __WeakSelf
    if (likeType == 1) {
        [MBProgressHUD showActivityMessageInWindow:@"matching..."];
        //防止重复点击
        self.collectionView.userInteractionEnabled = NO;
    }
    [[MBWhoLikeMeDataManager sharedManager] noticSayHiWithType:likeType userId:model.userCodeFriend ?: model.friendUserCode success:^(BOOL success) {
        weakSelf.collectionView.userInteractionEnabled = YES;
        [MBProgressHUD hideHUD];
        if (success && likeType == 1) {
            NSMatchViewController *matchViewController = [NSMatchViewController new];
            matchViewController.model = model;
            [weakSelf.currentViewController.navigationController pushViewController:matchViewController animated:YES];
            [self likePassResetData];
        }
    }];
    
    
    if (likeType == 2) {
        [self likePassResetData];
    }
}

- (void)likePassResetData {
    [[MBWhoLikeMeDataManager sharedManager].listDataArr removeObjectAtIndex:self.clickNum];
    [self.collectionView reloadData];
    if ([MBWhoLikeMeDataManager sharedManager].listDataArr.count == 0) {
        self.collectionView.hidden = YES;
        self.nullView.hidden = NO;
        self.usageNumView.hidden = YES;
        self.navigationController.tabBarItem.badgeValue = nil;//清空
    } else {
        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",[MBWhoLikeMeDataManager sharedManager].listDataArr.count];
    }
    [self.headerView resetState];
}

#pragma mark -- collectionView  delegate datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [MBWhoLikeMeDataManager sharedManager].listDataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MBWLMListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MBWLMListCell" forIndexPath:indexPath];
    MBWLMTopicModel *model = [MBWhoLikeMeDataManager sharedManager].listDataArr[indexPath.row];
    cell.model = model;
    __WeakSelf
    cell.passBlock = ^{
        weakSelf.clickNum = indexPath.row;
        [weakSelf likePassResetData];
    };
    return cell;
}

//设置每个section的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(MBHeightScale(10), MBWidthScale(16), MBHeightScale(10), MBWidthScale(16));
}

//设置列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(12);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(12);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((ScreenWidth-MBWidthScale(46))/2, MBHeightScale(250));
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([MBUserAccount defaultAccount].isVip) {
        self.clickNum = indexPath.row;
        //会员直接跳profile
        MBWLMTopicModel *model = [MBWhoLikeMeDataManager sharedManager].listDataArr[indexPath.row];
        NSModelDetailViewController *modelDetailVc = [NSModelDetailViewController new];
        modelDetailVc.modelStyle = WLMModelDetail;
        modelDetailVc.userId = model.friendUserCode ?: model.userCodeFriend;
        [self.navigationController pushViewController:modelDetailVc animated:YES];
        
    } else if ([[MBWhoLikeMeDataManager sharedManager].wlmNum integerValue] > 0) {
        self.clickNum = indexPath.row;
        //非会员 有次数 直接match
        MBWLMTopicModel *model = [MBWhoLikeMeDataManager sharedManager].listDataArr[indexPath.row];
        __WeakSelf
        //debugTest  wlm数据有限,划了就没了 临时注释
        [MBProgressHUD showActivityMessageInWindow:@"matching..."];
        //防止重复点击
        self.collectionView.userInteractionEnabled = NO;
        [[MBWhoLikeMeDataManager sharedManager] noticSayHiWithType:1 userId:model.userCodeFriend ?: model.friendUserCode success:^(BOOL success) {
            weakSelf.collectionView.userInteractionEnabled = YES;
            [MBProgressHUD hideHUD];
            if (success) {
                //非vip此处要扣减
                [MBWhoLikeMeDataManager sharedManager].wlmNum = [NSString stringWithFormat:@"%ld",[[MBWhoLikeMeDataManager sharedManager].wlmNum integerValue]-1];
                //悬浮次数状态变更
                if ([[MBWhoLikeMeDataManager sharedManager].wlmNum integerValue] == 0) {
                    weakSelf.usageNumView.hidden = YES;
                }
                weakSelf.usageNumView.numLab.text = [MBWhoLikeMeDataManager sharedManager].wlmNum;
                //
                NSMatchViewController *matchViewController = [NSMatchViewController new];
                matchViewController.model = model;
                [weakSelf.currentViewController.navigationController pushViewController:matchViewController animated:YES];
                //移除
                [self likePassResetData];
            }
        }];
    } else {
        //非会员 没次数 拉起会员购买
        [kKeyWindow addSubview:self.vipPopView];
        self.vipPopView.index = 1;
        self.vipPopView.hidden = NO;
        /**
         埋点
         WLM点击成为会员拉起会员订阅 WLM_Unlock_Sub
         */
        [[NSIOApiManager sharedManager] setIOWithEventName:@"WLM_Unlock_Sub"];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionFooter] && [MBWhoLikeMeDataManager sharedManager].listDataArr.count > 0) {
        NSWLMFooterView *reviewHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"NSWLMFooterView" forIndexPath:indexPath];
        return reviewHeadView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if ([MBWhoLikeMeDataManager sharedManager].listDataArr.count > 0) {
        return CGSizeMake(ScreenWidth, MBHeightScale(40));
    }
    return CGSizeMake(0, 0);
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.headerView];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom).offset(MBHeightScale(10));
//        make.left.mas_equalTo(MBWidthScale(16));
//        make.width.mas_equalTo(ScreenWidth-MBWidthScale(32));
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    [self.view addSubview:self.nullView];
    [self.nullView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom).offset(MBHeightScale(0));
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    [self.view addSubview:self.usageNumView];
    [self.usageNumView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-MBHeightScale(47));
        make.right.mas_equalTo(MBWidthScale(-20));
        make.width.height.mas_equalTo(MBHeightScale(54));
    }];
    
    //pop
    [self vipPopView];
}

#pragma mark - Setter && Getter
- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}

- (NSWLMHeaderView *)headerView {
    if (!_headerView) {
        __WeakSelf
        _headerView = [NSWLMHeaderView new];
        _headerView.vipBlock = ^{
            [kKeyWindow addSubview:weakSelf.vipPopView];
            weakSelf.vipPopView.index = 1;
            weakSelf.vipPopView.hidden = NO;
        };
    }
    return _headerView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[MBWLMListCell class] forCellWithReuseIdentifier:@"MBWLMListCell"];
        [_collectionView  registerClass:[NSWLMFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"NSWLMFooterView"];
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if (![MBUserAccount defaultAccount].isVip) {
                //非会员 没次数 拉起会员购买
                [kKeyWindow addSubview:self.vipPopView];
                self.vipPopView.index = 1;
                self.vipPopView.hidden = NO;
                [self.collectionView.mj_footer endRefreshing];
            } else {
                [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        }];
    }
    return _collectionView;
}

- (NSWLMNullView *)nullView {
    if (!_nullView) {
        __WeakSelf
        _nullView = [NSWLMNullView new];
        _nullView.refreshBlock = ^{
            [weakSelf getListData];
        };
    }
    return _nullView;
}

- (NSUsageNumView *)usageNumView {
    if (!_usageNumView) {
        _usageNumView = [NSUsageNumView new];
        _usageNumView.hidden = YES;
    }
    return _usageNumView;
}

- (NSVipPopView *)vipPopView {
    if (!_vipPopView) {
        __WeakSelf
        _vipPopView = [[NSVipPopView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        _vipPopView.index = 1;
        _vipPopView.payBlock = ^{
            //支付成功 刷新列表
            [weakSelf getListData];
            weakSelf.isVip = YES;
            /**
             埋点
             WLM点击成为会员拉起会员订阅支付成功 WLM_Unlock_Subsuccess
             */
            [[NSIOApiManager sharedManager] setIOWithEventName:@"WLM_Unlock_Subsuccess"];
        };
    }
    return _vipPopView;
}

- (MBRefreshGifHeaderLottie *)refreshGifHeaderLottie {
    if (!_refreshGifHeaderLottie) {
        _refreshGifHeaderLottie = [MBRefreshGifHeaderLottie new];
    }
    return _refreshGifHeaderLottie;
}
@end
